<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    #danmu {
      width: 1200px;
      height: 400px;
      background: skyblue;
      position: relative;
    }

    p {
      position: absolute;
    }
  </style>
</head>

<body>
  聊天室
  <div id="danmu">



  </div>
  <div>
    <input type="text" id="mytxt"><button id="send">发送</button>
  </div>
  <script>
    // 前端的webScoket连接后端
    var wsc = new WebSocket("ws://169.254.184.38:88")
    // 连接后台ws服务器成功的时间
    wsc.onopen = function () {
      console.log("连接到ws服务器了")
    }
    // 接受ws服务器返回的数据
    var danmu = document.getElementById("danmu");
    wsc.onmessage = function (msg) {
      console.log(msg.data)
      var p = document.createElement("p");
      p.innerHTML = msg.data;
      p.style.top = Math.floor(Math.random() * 300) + "px";
      p.style.color = "#" + Math.floor(Math.random() * 0xFFFFFF).toString(16)
      var x = 0;
      // left值改变
      var timer = setInterval(() => {
        x++;
        p.style.left = x + "px"
        if (x >= 900) {
          p.remove();
          clearInterval(timer)
        }
      }, 10);

      danmu.appendChild(p)
    }


    var send = document.getElementById("send");
    send.onclick = function () {
      var mytxtVal = document.getElementById("mytxt").value;
      if (mytxtVal.length > 10) {
        alert("你输入的字符太长")
      } else {
        wsc.send(mytxtVal)
      }
    }

  </script>
</body>

</html>